<template>
  <Temp @clear="clear" @close="close">
    <div class="sightline">
      <div
        @click="activeTool(item.title)"
        v-for="item in list"
        :key="item.title"
        :style="{
          color:
            active === item.title
              ? activeColor
              : defaultColor
        }"
      >
        <Icon
          :title="item.title"
          :name="item.icon"
          :font-size="iconSize"
        />
        <span>{{ item.title }}</span>
      </div>
    </div>
  </Temp>
</template>

<script>
import Temp from '../temp'
import Icon from '@/components/icon'
import { getAction } from '@/utils/helper'

const viewer = {}
const scene = {}
const canvas = {}
const sightline = {}

let addViewFlag = false // 当前点击状态是否是 添加观察点
let addTargetFlag = false // 当前点击状态是否是 添加目标点
let num = 0 // 添加的目标点的点号
let couldRemove = false // 是否能移除目标点
let handlerPoint = null
let handler = null

export default {
  components: {
    Temp,
    Icon
  },
  inject: ['viewerId'],
  data() {
    return {
      iconSize: 20,
      activeColor: 'rgba(0, 210, 255, 1)',
      defaultColor: '#D2E6F0',
      active: '',
      list: [
        {
          title: '添加观察点',
          icon: 'add'
        },
        {
          title: '添加目标点',
          icon: 'add'
        }
      ]
    }
  },
  async created() {
    const { toolManager } = await getAction(this.viewerId)
    viewer[this.viewerId] = toolManager.viewer
    scene[this.viewerId] = toolManager.scene
    canvas[this.viewerId] = toolManager.canvas
    sightline[this.viewerId] = new Cesium.Sightline(
      toolManager.scene
    )
    sightline[this.viewerId].lineWidth = 5
    sightline[this.viewerId].build()

    handlerPoint = new Cesium.DrawHandler(
      viewer[this.viewerId],
      Cesium.DrawMode.Point
    )
    handlerPoint.drawEvt.addEventListener((result) => {
      // 添加观察点
      if (addViewFlag) {
        // var point = result.object
        // point.show = false;
        const position = result.object.position

        // 将获取的点的位置转化成经纬度
        const cartographic =
          this.Cartesian2toDegrees(position)

        // 设置观察点
        sightline[this.viewerId].viewPosition = cartographic
        addViewFlag = false

        this.active = ''
      }
      handlerPoint.deactivate()
    })

    handler = new Cesium.ScreenSpaceEventHandler(
      canvas[this.viewerId]
    )
  },
  methods: {
    close() {
      this.$emit('close')
    },
    clear() {
      addViewFlag = false
      addTargetFlag = false
      handlerPoint.clear()
      num = 0
      viewer[this.viewerId].entities.removeAll()
      if (couldRemove) {
        sightline[this.viewerId].removeAllTargetPoint()
        couldRemove = false
      }
      viewer[this.viewerId].enableCursorStyle = true
    },
    activeTool(title) {
      if (this.active === title) {
        this.clear()
      } else {
        // this.clear()
        this.active = title
        switch (title) {
          case '添加观察点':
            addViewFlag = true
            if (handlerPoint.active) {
              return
            }
            viewer[this.viewerId].entities.removeAll()
            if (couldRemove) {
              sightline[
                this.viewerId
              ].removeAllTargetPoint()
            }
            handlerPoint.activate()

            if (addViewFlag || addTargetFlag) {
              viewer[
                this.viewerId
              ].enableCursorStyle = false
              viewer[this.viewerId]._element.style.cursor =
                ''
            }
            break
          case '添加目标点':
            addViewFlag = false
            addTargetFlag = true

            if (addViewFlag || addTargetFlag) {
              viewer[
                this.viewerId
              ].enableCursorStyle = false
              viewer[this.viewerId]._element.style.cursor =
                ''
            }

            // 鼠标点击事件，添加点
            handler.setInputAction((e) => {
              const position = scene[
                this.viewerId
              ].pickPosition(e.position)
              this.addTarget(position)
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

            // 鼠标移动事件，更新点
            handler.setInputAction((evt) => {
              // console.log('鼠标移动:', 'startPosition:', evt.startPosition, 'endPosition:', evt.endPosition)
              // 鼠标移动，更新最后一次添加的目标点的位置
              const position = scene[
                this.viewerId
              ].pickPosition(evt.endPosition)

              if (num > 0) {
                sightline[this.viewerId].removeTargetPoint(
                  'point0'
                )
                const cartographic =
                  this.Cartesian2toDegrees(position)

                // var flag =
                sightline[this.viewerId].addTargetPoint({
                  position: cartographic,
                  name: 'point0'
                })
              }
            }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

            // 鼠标右键事件，结束
            handler.setInputAction(() => {
              viewer[this.viewerId].enableCursorStyle = true

              handler.removeInputAction(
                Cesium.ScreenSpaceEventType.MOUSE_MOVE
              )
              handler.removeInputAction(
                Cesium.ScreenSpaceEventType.LEFT_CLICK
              )

              this.active = ''
            }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
            break
          default:
            break
        }
      }
    },
    // 添加通视点
    addTarget(CartesianPosition) {
      if (addViewFlag === false && addTargetFlag) {
        num += 1
        // 将获取的点的位置转化成经纬度
        const cartographic = this.Cartesian2toDegrees(
          CartesianPosition
        )
        // 添加目标点
        const name = 'point' + num
        // var flag =
        sightline[this.viewerId].addTargetPoint({
          position: cartographic,
          name: name
        })
        couldRemove = true
      }
    },
    // 笛卡尔转换为经纬度
    Cartesian2toDegrees(position) {
      const cartographic =
        Cesium.Cartographic.fromCartesian(position)
      const longitude = Cesium.Math.toDegrees(
        cartographic.longitude
      )
      const latitude = Cesium.Math.toDegrees(
        cartographic.latitude
      )
      const height = cartographic.height
      return [longitude, latitude, height]
      // return [longitude, latitude, 0]
    }
  }
}
</script>

<style lang="scss" scoped>
.sightline {
  display: flex;
  align-items: center;

  & > div:last-child {
    margin-left: 10px;
  }

  & > div {
    display: flex;
    align-items: center;

    & > span {
      margin-left: 4px;
      font-size: 14px;
      word-break: keep-all;
      cursor: pointer;
    }
  }
}
</style>
